
#include "ACache.h"

CACache* CACache::_sharedCache = null;

CACache::CACache(void)
{
	GUARD_FUNCTION();

	CCLOGINFO("CACache created");
	_cache = new CAStringMap< CAStringMap< CCObject > >();
	_sharedCache = this;
}

CACache::~CACache(void)
{
	int n = 0;
	CCDictElement* pElement = NULL;
	CCDICT_FOREACH(_cache, pElement)
	{
		CAStringMap<CCObject>* pgroup = (CAStringMap<CCObject>*)pElement->getObject();
		_Assert(pgroup);
		n += pgroup->count();
	}
	_Info("CACache release %d objects", n);
	_cache->release();
	_cache = null;
}

CACache& CACache::sharedCache()
{
	GUARD_FUNCTION();

	if (null == _sharedCache)
		_sharedCache = new CACache();
	return *_sharedCache;
}

CCObject* CACache::hit(const char* key, const char* group)
{
	CAStringMap<CCObject>* pgroup;

	if (null == group)
	{
#if defined(_CC_OLD_)
		_cache->begin();
		CAString g;
		while (null != (pgroup = 
			//(CAStringMap<CCObject>*)
			_cache->next(&g)))
		{
			_Assert(pgroup);
			CCObject* pobj = pgroup->objectForKey(key);
			if (null != pobj)
			{
				return pobj;
			}
		}
		_cache->end();
#else
		CCDictElement* pElement = NULL;
		CCDICT_FOREACH(_cache, pElement)
		{
			pgroup = (CAStringMap<CCObject>*)pElement->getObject();
			_Assert(pgroup);
			CCObject* pobj = pgroup->objectForKey(key);
			if (null != pobj)
			{
				return pobj;
			}
		}
#endif
		return null;
	}

	pgroup = (CAStringMap<CCObject>*)_cache->objectForKey(group);
	return (null == pgroup) ? null : pgroup->objectForKey(key);
}

void CACache::put(const char* key, CCObject* pobj, const char* group)
{
	GUARD_FUNCTION();

	CAStringMap<CCObject>* pgroup;

	pgroup = (CAStringMap<CCObject>*)_cache->objectForKey(group);
	if (null == pgroup)
	{
		pgroup = new CAStringMap<CCObject>();
		//pgroup->autorelease();
		_cache->setObject(pgroup, group);
		pgroup->release();
	}
	pgroup->setObject(pobj, key);
	return;
}
